package hao.d0319;

public class BankTest {
    volatile boolean hasBank =  false;
    Object flag = new Object();//锁
    Object flag2 = new Object();
    static double money =1000;
    Thread counter = new Thread(()->{
        while (true){
            synchronized (flag) {
                if (!hasBank) {
                    try {
                        flag.wait();//阻塞
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("A取走了100元，还剩" + money + "元");
                    hasBank = false;
                }
            }
        }
    });
    Thread ATM = new Thread(()->{
        while (true) {
            synchronized (flag) {
                if (!hasBank) {
                    try {
                        flag.wait();//阻塞
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("B取走了100元，还剩" + money + "元");
                    hasBank = false;
                    if (money == 0) {
                        System.out.println("尊敬的客户，您的账户余额不足。");
                        System.exit(0);
                    }
                }
            }
        }
    });
    Thread Save = new Thread(()->{
        while (money>0) {
            synchronized (flag2) {
                if (!hasBank) {
                    try {
                        flag2.wait();//阻塞
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("C存入200元，还剩" + money + "元");
                    hasBank = false;
                }
            }
        }
    });
    Thread ID= new Thread(()->{
        while (money >0) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            hasBank = true;
            synchronized (flag) {
                money=money-100;
                flag.notify();//唤醒
            }
        }
    });
    Thread ID2= new Thread(()->{
        while (true) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            hasBank = true;
            synchronized (flag2) {
                money=money+200;
                flag2.notify();//唤醒
            }
        }
    });

    public static void main(String[] args) {
        BankTest bankTest = new BankTest();
        Thread t1 = new Thread(bankTest.counter);
        Thread t2 = new Thread(bankTest.ATM);
        Thread t3 = new Thread(bankTest.Save);
        bankTest.ID.start();
        bankTest.ID2.start();
        t1.start();
        t2.start();
        t3.start();
    }
}
